<template>
  <div class="layers">
    <div class="mark" v-show="isDowning"></div>
    <p class="layers_tit tit14">图层</p>
    <div @click="addTextClick" class="picture_button clickdiv">
      <img :src="img.xinjianwenzi" alt="" />
      <span>添加文字</span>
    </div>
    <div class="picture_button butt clickdiv">
      <img :src="img.xinjian" alt="" />
      <span>添加本地图片</span>
      <input type="file" @change="addPicClick($event)" />
    </div>
    <div class="">
      <p class="picture_layer_P">图片</p>
      <!-- 图片工具-层级关系 -->
      <div class="picture_layers" v-show="listImg == '' ? false : true">
        <div class="">
          <div
            class="picture_layer"
            v-for="(v, i) in listImg"
            :key="i"
            :style="{
              background: v.config.name.indexOf('imgback')
                ? '#fff'
                : ' #e9e9e9',
            }"
            @click="picturelayerclick(v.config.name)"
          >
            {{ v.config.picname }}
          </div>
        </div>
      </div>
    </div>
    <div class="" v-show="listNote == '' ? false : true">
      <p class="picture_layer_P">文字</p>
      <!--    content页面-->
      <div class="picture_layers">
        <div class="">
          <div v-for="(v, i) in listNote" :key="i">
            <template v-if="$route.path == '/content'">
              <el-tooltip
                v-if="formruleArr.length > 0"
                class="item"
                effect="dark"
                :content="formulaArrText[i]"
                placement="bottom"
              >
                <div
                  class="picture_layer"
                  :style="{
                    background: v.config.name.indexOf('imgback')
                      ? '#fff'
                      : ' #e9e9e9',
                  }"
                  @click="picturelayerclick(v.config.name, i, rules)"
                >
                  {{ v.config.originaltext }}
                </div>
              </el-tooltip>
              <div
                v-else
                class="picture_layer"
                :style="{
                  background: v.config.name.indexOf('imgback')
                    ? '#fff'
                    : ' #e9e9e9',
                }"
                @click="picturelayerclick(v.config.name, i, rules)"
              >
                {{ v.config.originaltext }}
              </div>
            </template>
            <template v-else>
              <div
                class="picture_layer"
                :style="{
                  background: v.config.name.indexOf('imgback')
                    ? '#fff'
                    : ' #e9e9e9',
                }"
                @click="picturelayerclick(v.config.name, i, rules)"
              >
                {{ v.config.originaltext }}
              </div>
            </template>
            <div style="display: flex" v-if="$route.path == '/template'">
              <span style="width: 150px; line-height: 35px">文本框公式：</span>
              <el-input
                @blur="textformula(i)"
                v-model="formruleArr[i]"
                @input="inpformruleArr"
                placeholder="请输入文本框公式"
              >
              </el-input>
            </div>
            <span
              style="margin-left: 100px; line-height: 35px; color: green"
              v-if="formruleArrShow && formruleArrShow[i] == 1"
              >公式格式正确</span
            >
            <span
              style="margin-left: 100px; line-height: 35px; color: red"
              v-else-if="formruleArrShow && formruleArrShow[i] == 0"
              >公式格式有误</span
            >
            <!-- <span style="margin-left: 100px; line-height: 35px" v-else></span> -->
          </div>
        </div>
      </div>
      <!--    template页面-->
      <div v-show="listNote && allTextShow && $route.path == '/content'">
        <p class="picture_layer_P" style="font-size:20px;">请输入文本内容：</p>

        <div class="text_con_all_text">
          <textarea v-model="alltext" class="alltext" placeholder="请输入文本">
          </textarea>
        </div>
        <div class="text_queding_bot">
          <div
            class="text_queding"
              style="margin: 10px 0;"
              @click="confrimtext"
            >
            确定
          </div>
        </div>
        <div class="text_queding_bot">
          <div
            class="text_queding"
              style="margin: 10px 0;"
              @click="downloadAll(1)"
              v-if="downloadAllShow"
            >
            批量下载
          </div>
        </div>
        <div class="text_queding_bot">
          <div
            class="text_queding"
              style="margin: 10px 0;"
              @click="pasteText()"
            >
            粘贴文字
          </div>
        </div>
      </div>
    </div>
    <div class="">
      <p class="picture_layer_P">LOGO</p>
      <!-- logo工具-层级关系 -->
      <div class="picture_layers" v-show="listlogo == '' ? false : true">
        <div class="">
          <div
            class="picture_layer"
            v-for="(v, i) in listlogo"
            :key="i"
            :style="{
              background: v.config.name.indexOf('imgback')
                ? '#fff'
                : ' #e9e9e9',
            }"
            @click="picturelayerclick(v.config.name, i)"
          >
            {{ v.config.picname }}
          </div>
        </div>
      </div>
    </div>
    <p v-if="dashitou26" class="picture_layer_P">请输入模板内容</p>
    <div v-if="dashitou26" class="text_con">
      <div
        class="text_blur"
        contenteditable="plaintext-only"
        @blur="textconBlur"
        v-text="listNote[0].config.originaltext"
      ></div>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations,mapGetters } from "vuex";
import mixin from "@/utils/mixin";
import { maps, areaPatt, colPatt, rowPatt } from "@/assets/js/map";
let ClipBoards = [];
let num = 0;
export default {
  mixins: [mixin],
  props: ["formulafa", "stageNode", "temid"],
  data() {
    return {
      dashitou26: false,
      context: "",
      verticaltext: false,
      canSave: false,
      alltext: "",
      //多段文字
      formulaArrText: [],
      poetry: [],
      /**
       * 批量下载按钮的显示
       */
      downloadAllShow: false,
      /**
       * 文本框格式的提示
       */
      formruleArrShow: [],
      /**
       * 多段公式
       */
      formruleArr: [],
      /**
       * 将多张图片保存到剪切板
       */
      ClipBoards: [],
      /**
       * 用于竖向显示的内容
       */
      turntext:"",
      /**
       * 竖向转化输入框显示与隐藏
       */
      // turntextShow:0,
      /**
       * 文本内容输入框的显示yuyinc
       */
      allTextShow:true,
      /**
       * 下载中遮罩层
       */
      isDowning:false
    };
  },
  computed: {
    ...mapState("templateStage", [
      "listImg",
      "imgtool",
      "konvaid",
      "listNote",
      "listlogo",
      "historylist",
      "templateAllText",
      "listNottetool",
      "rules",
    ]),
    ...mapGetters("templateStage",['getRules']),
    rules: {
      get(i) {
        if (!isNaN(i)) {
          var arr = JSON.parse(this.$store.state.templateStage.rules);
          return arr[i];
        } else {
          return this.$store.state.templateStage.rules;
        }
      },
      set(obj) {
        this.$store.state.templateStage.rules = obj;
      },
    },
  },
  methods: {
    ...mapMutations("templateStage", [
      "setRules",
      "savetemplateAllText",
      "switchsavetoClipBoardBtn",
    ]),
    inpformruleArr(){},
    /**
     * 粘贴文字到智能文本框
     */
    async pasteText(){
      let clipText = await navigator.clipboard.readText()
      if (clipText) {
        let rnpatt = /\r\n/;
        let rnflag = rnpatt.test(clipText)
        if (rnflag) {
          clipText = clipText.replaceAll("\r\n","\n")
        }
        this.alltext = clipText;
        this.confrimtext()
      }
    },
    /**
     * 公式输入
     */
    textformula(i) {
      // let list = this.formulaArrText;
      let formrule = this.formrule;
      var vals = this.formruleArr[i];
      let qujian = areaPatt.test(vals);
      let lie = colPatt.test(vals);
      let hang = rowPatt.test(vals);
      let isAll = (vals == "=all" || vals == "=ALL");
      this.canSave = false;
      if (qujian || lie || hang || isAll) {
        this.$nextTick(() => {
          this.formruleArrShow[i] = 1;
          this.$message.success("公式格式正确");
        });
      } else if (!vals) {
        this.formruleArrShow[i] = -1;
      } else {
        this.$nextTick(() => {
          this.$message.error("公式格式错误");
          this.formruleArrShow[i] = 0;
        });
      }
      // console.log(this.formruleArr);
      // console.log("设置");
      this.setRules(this.formruleArr);
      this.formrule = formrule;
      this.canSave = true;
    },
    /**
     * 确认公式按钮
     */
    confrimtext() {
      // if (this.historylist.length == 0) this.$createstage.saveHistory(this);
      // console.log(this.alltext);
      // console.log(this.formulaArrText);
      // console.log(this.formruleArr);
      // var formulaArrText = JSON.parse(sessionStorage.getItem("formulaArrText"))
      // console.log(formulaArrText);
      if (!this.alltext) {
        this.$message.error("请先输入模板文本再提交");
        return;
      }
      this.$emit("crearImgs");
      this.savetemplateAllText(this.alltext);
      var poretyNum = this.alltext.split("\n\n").length;
      if (poretyNum > 1) {
        this.switchsavetoClipBoardBtn(false);
      } else {
        this.switchsavetoClipBoardBtn(true);
      }

      //公式
      var strformulaArrText = this.formulaArrText;
      // console.log(strformulaArrText);
      if (strformulaArrText) {
        this.rules = strformulaArrText;
        this.setRules(strformulaArrText);
        //待分配的文字
        for (let index = 0; index < strformulaArrText.length; index++) {
          let formula = strformulaArrText[index];
          if (formula) {
            this.distribution(formula, index);
          }
        }
      }
    },
    /**
     * 改变字体方向
     */
    // allturntext() {
    //   let alltext = this.turntext;
    //   let funtext = "";
    //   var poretys = alltext.split("\n\n");
    //   for (let index = 0; index < poretys.length; index++) {
    //     let porety = poretys[index];
    //     let rows = porety.split("\n");
    //     let arr = [];
    //     var res = [];
    //     for (let index = 0; index < rows.length; index++) {
    //       const element = rows[index];
    //       let row = element.split("");
    //       arr.push(row);
    //     }
    //     let maxlength = 0;
    //     for (let index = 0; index < arr.length; index++) {
    //       if (arr[index].length > maxlength) {
    //         maxlength = arr[index].length;
    //       }
    //     }
    //     for (let index = 0; index < arr.length; index++) {
    //       for (let jndex = 0; jndex < maxlength; jndex++) {
    //         if (!arr[index][jndex]) {
    //           arr[index][jndex] = "";
    //         }
    //       }
    //     }
    //     for (var i = 0; i < arr[0].length; i++) {
    //       res[i] = [];
    //     }
    //     for (var row = 0; row < arr.length; row++) {
    //       for (var col = 0; col < arr[row].length; col++) {
    //         res[col][row] = arr[row][col];
    //       }
    //     }
    //     let restext = "";
    //     for (let index = 0; index < res.length; index++) {
    //       const element = res[index];
    //       var str = element.join("");
    //       restext = restext + str + "\n";
    //     }
    //     // console.log(restext);
    //     if (index < poretys.length) {
    //       funtext = funtext + restext + "\n";
    //     }
    //   }
    //   funtext = funtext.trim();
    //   this.alltext = funtext;
    //   this.confrimtext();
    // },
    /**
     * 分配文字
     */
    distribution(fixformula,index){
      let patt =/^=[a-zA-Z]\d+:[a-zA-Z]\d+$/;//区间
      let patt1 =/^=[a-zA-Z]:[a-zA-Z]$/;// A:B第一列到第二列
      let patt2 =/^=\d+:\d+$/;// 2:3第二行到第三行
      let qujian = patt.test(fixformula)
      let lie = patt1.test(fixformula)
      let hang = patt2.test(fixformula)
      let copyAllText = (fixformula == "=all" ||fixformula == "=ALL")
      let calcArr =[];
      let position = fixformula.substring(1).split(":");
      let saveText = this.alltext.trim();
      console.log(saveText);
      let cancalc = false;//是否要公式计算
      let str="";
      
      let poetry = saveText.split("\n\n");
      this.poetry = poetry
      //多段文字才有批量下载
      this.downloadAllShow= poetry.length>1
      let row = saveText.split("\n");
      let saveArr = []
      for (let i = 0; i < row.length; i++) {
        let strr = row[i].split("")
        let arr = []
        for (let j = 0; j < strr.length; j++){
          arr.push(strr[j])
        }
        saveArr.push(arr)
      }
      let maxCols = 0;
      let maxRows = saveArr.length;
      for (let index = 0; index < saveArr.length; index++) {
        const element = saveArr[index];
        if (element.length>maxCols) {
          maxCols=element.length
        }
      }
      if(qujian){
        cancalc = true;
        let en = /[a-zA-Z]+/;
        let math = /\d+/;
        let startx = position[0].match(en)[0]
        let starty = position[0].match(math)[0]*1
        let endx = position[1].match(en)[0]
        let endy = position[1].match(math)[0]*1;
        let aa = maps[startx]-1;
        let bb = starty-1;
        let cc = maps[endx]-1;
        let dd = endy-1;
        cc = cc>maxRows-1?maxRows-1:cc;
        dd = dd>maxCols-1?maxCols-1:dd;
        // console.log("区间");
        // console.log(aa ,"-",cc,"行");
        // console.log(bb ,"-",dd,"列");
        for(let i=aa;i<=cc;i++){
          let arr = [];
          for(let j=bb;j<=dd;j++){
            if (saveArr&&saveArr[i][j]) {
              arr.push(saveArr[i][j])
            }else{
              arr.push("")
            }
          }
          calcArr.push(arr)
        }
        
        for (let index = 0; index < calcArr.length; index++) {
          let row=""
          for (let jndex = 0; jndex < calcArr[index].length; jndex++) {
            row = row + calcArr[index][jndex]
          }
          
          str = str + row + "\n"
        }
        // console.log(str);
      }
      else if(lie){
        let aa = position[0];
        let bb = position[1];
        let beg = maps[aa]-1;
        let end = maps[bb]-1;
        cancalc = true;
        end = end>maxCols?maxCols:end;
        for (let index = 0; index <saveArr.length; index++) {
            let row=""
            for (let jndex=beg;jndex<=end;jndex++){
              if(saveArr[index][jndex]==""){
                continue;
              }else {
                if(saveArr[index][jndex]==" "){
                  row = row + " "
                }else {
                  row = row + saveArr[index][jndex]
                }
              }
            }
            str = str + row + "\n"
        }
      }
      else if (hang){
        cancalc = true;
        for (let index = position[0]-1; index <=position[1]-1; index++) {
          let row=""
          for (let jndex=0;jndex<saveArr[index].length;jndex++){
            if(saveArr[index][jndex]==""){
              continue;
            }else {
              if(saveArr[index][jndex]==" "){
                row = row + " "
              }else {
                row = row + saveArr[index][jndex]
              }
            }
          }
          str = str + row + "\n";
        }
      }
      else if(copyAllText){
        cancalc = true;
        str = saveText;
        str = poetry[0];
      }else{
        cancalc = false;
      }
      
      /**
       * 一张文字不同文本框
       */
      var obj = {
        str:str,
        index:index
      }
      if(cancalc){
        // console.log(str);
        let that = this;
        this.drowAllListtext(obj.str,obj.index)
      }
    },
    /**
     * 设置文字信息
     */
    drowAllListtext(text,index){
      let list = this.listNote;
      console.log(this.listNote);
      let lineNum = text.split("\n").length
      for (let jndex = 0; jndex < list.length; jndex++) {
        if (index==jndex) {
          list[index].config.originaltext = text;
          if (list[index].config.verticaltext) {
            //竖向显示
            text = this.$datatools.TtoDBC(text);
            text = this.$datatools.lineFeedCutData(text);
          }
          list[index].config.text = text;
          let lineNum = text.split("\n").length;
          list[index].config.height = list[index].config.fontSize * lineNum +
                lineNum *( list[index].config.lineHeight + 2) * list[index].config.fontSize;
          list[index].config.width =
          list[index].config.fontSize * list[index].config.spacingNum +
            (list[index].config.spacingNum + 1) * list[index].config.letterSpacing;
        }
      }
      this.$store.commit("templateStage/SETLISTNOTE", list);
    },
    /**
     * 批量下载按钮
     */
    downloadAll(type) {
      this.isDowning = true;
      this.savetemplateAllText(this.alltext);
      //公式
      var strformulaArrText = this.formulaArrText;
      this.rules = strformulaArrText;
      this.setRules(strformulaArrText);
      this.poetry =
        this.poetry.length > 0 ? this.poetry : this.alltext.split("\n\n");
      //待分配的文字
      for (let index = 0; index < strformulaArrText.length; index++) {
        let formula = strformulaArrText[index];
        if (formula) {
          this.setParagraph(formula, index,strformulaArrText.length, type);
        }
      }
    },
    /**
     * 批量文字分配
     * index 段落
     * type==1 批量下载到本地
     * type==0 批量生成图片
     */
    setParagraph(fixformula,pageindex,formulalength,type){
      let poetry = this.poetry;
      let poetryNum = poetry.length;
      let list = this.listNote;
      let that = this;
      
      for (let kndex = 0; kndex < poetryNum;kndex++) {
            setTimeout(function () {
              let saveText = poetry[kndex] 
              // console.log(saveText);
              let row = saveText.split("\n");
              let saveArr = []
              let str="";
              let cancalc = false;
              let patt =/^=[a-zA-Z]\d+:[a-zA-Z]\d+$/;//区间
              let patt1 =/^=[a-zA-Z]:[a-zA-Z]$/;// A:B第一列到第二列
              let patt2 =/^=\d+:\d+$/;// 2:3第二行到第三行
              let qujian = patt.test(fixformula)
              let lie = patt1.test(fixformula)
              let hang = patt2.test(fixformula)
              let copyAllText = (fixformula == "=all" ||fixformula == "=ALL")
              let calcArr =[];
              let position = fixformula.substring(1).split(":")
              for (let i = 0; i < row.length; i++) {
                let strr = row[i].split("")
                let arr = []
                for (let j = 0; j < strr.length; j++){
                  arr.push(strr[j])
                }
                saveArr.push(arr)
              }   
              if(qujian){
                cancalc = true;
                let en = /[a-zA-Z]+/;
                let math = /\d+/;
                let startx = position[0].match(en)[0]
                let starty = position[0].match(math)[0]*1
                let endx = position[1].match(en)[0]
                let endy = position[1].match(math)[0]*1;
                let aa = maps[startx]-1;
                let bb = starty-1;
                let cc = maps[endx]-1;
                let dd = endy-1;
                for(let i=aa;i<=cc;i++){
                  let arr = [];
                  for(let j=bb;j<=dd;j++){
                    if (saveArr&&saveArr[i][j]) {
                      arr.push(saveArr[i][j])
                    }else{
                      arr.push("")
                    }
                  }
                  calcArr.push(arr)
                }
                for (let index = 0; index < calcArr.length; index++) {
                  let row=""
                  for (let jndex = 0; jndex < calcArr[index].length; jndex++) {
                    row = row + calcArr[index][jndex]
                  }
                  str = str + row + "\n"
                }
              }
              else if(lie){
                let aa = position[0];
                let bb = position[1];
                let beg = maps[aa]-1;
                let end = maps[bb]-1;
                cancalc = true;
                for (let index = 0; index <saveArr.length; index++) {
                    let row=""
                    for (let jndex=beg;jndex<=end;jndex++){
                      if(saveArr[index][jndex]==""){
                        continue;
                      }else {
                        if(saveArr[index][jndex]==" "){
                          row = row + " "
                        }else {
                          row = row + saveArr[index][jndex]
                        }
                      }
                    }
                    str = str + row + "\n"
                }
              }
              else if (hang){
                cancalc = true;
                for (let index = position[0]-1; index <=position[1]-1; index++) {
                  let row=""
                  for (let jndex=0;jndex<saveArr[index].length;jndex++){
                    if(saveArr[index][jndex]==""){
                      continue;
                    }else {
                      if(saveArr[index][jndex]==" "){
                        row = row + " "
                      }else {
                        row = row + saveArr[index][jndex]
                      }
                    }
                  }
                  str = str + row + "\n";
                }
              }
              else if(copyAllText){
                cancalc = true;
                str = saveText;
              }else{
                cancalc = false;
              }
              
              var obj = {str:str,index:pageindex}
              if(cancalc){
                let lineNum = obj.str.split("\n").length;
                for (let jndex = 0; jndex < list.length; jndex++) {
                   if (pageindex==jndex) {
                    let text = obj.str
                    list[pageindex].config.originaltext = text
                    list[pageindex].config.height = lineNum*100;
                    list[pageindex].config.width = 1000;
                    if (list[pageindex].config.verticaltext) {
                        //竖向显示
                      text = that.$datatools.TtoDBC(text);
                      text = that.$datatools.lineFeedCutData(text);
                    }
                    list[pageindex].config.text = text;
                  }
                }
                num++;
                if (num%2==0&&formulalength!=1) {
                  return
                }
                /**
                 * type==1 下载到本地
                 * type==0 保存到剪切板
                 */
                if(type){
                  that.downloadParagraph(list,kndex)
                  if(kndex+1==poetryNum){
                    setTimeout(() => {
                      that.isDowning = false;
                    }, 500);
                  }else{
                    that.isDowning = true;
                  }
                }else{
                  if (kndex==0) {
                    that.ClipBoards = [];
                    ClipBoards = [];
                  }
                  setTimeout(() => {
                    let stage = that.stageNode;
                    let dataURL = stage.toDataURL({ pixelRatio: 1 });
                    that.$message.success("成功剪切第"+(kndex*1+1)+"张")
                    console.log(dataURL);
                    ClipBoards.push(dataURL)
                    // fetch(dataURL).then(data=>{
                    //   console.log(data.url);
                    //   ClipBoards.push(data.url)
                    // });
                    let poetryNum = that.poetry.length
                    if(kndex+1==poetryNum){
                      that.ClipBoards = ClipBoards;
                      that.$nextTick(()=>{
                        that.copyInfo(ClipBoards)
                      })
                    }
                  }, 50);
                }
              }
            }, 2000 * kndex);
      }
    },
    copyInfo(ClipBoards) {
      // console.log(ClipBoards);
      this.$emit("sendNode", ClipBoards);
      // console.log(ClipBoards);
      setTimeout(() => {
        // let dom = document.getElementById("__imgDiv")
        // if(!dom){
        //   dom = document.createElement('div')
        //   dom.id = '__imgDiv';
        // }
        // dom.setAttribute('style',`
        // z-index: 100;
        // position: fixed;
        // bottom:50%;
        // width:100vw;
        // display:felx;
        // height:100px;
        // `)

        let child = [];
        for (let index = 0; index < ClipBoards.length; index++) {
          const element = ClipBoards[index];
          child.push(
            `<img src="${element}" style="width:100px;height:100px;margin:0 20px;/>`
          );
        }
        var str = child.join("");
        console.log(str);
        // navigator.clipboard.setData('URL', ClipBoards[0]);
        fetch(ClipBoards[0]).then((data) => {
          data.blob().then((blob) => {
            navigator.clipboard
              .write([
                new ClipboardItem({
                  [blob.type]: blob,
                }),
              ])
              .then((res) => {
                console.log(res);
                alert("复制成功");
              });
          });
        });

        // console.log(dom);
        // document.body.insertBefore(dom,document.body.lastChild)
        // let dom = document.getElementById('__imgDiv')
        // console.log(dom)
        // let selection = window.getSelection();
        // let range = document.createRange();
        // range.selectNodeContents(dom);
        // selection.addRange(range);
        // document.execCommand("copy");
        // selection.removeAllRanges();
      }, 1000);
    },
    blobToBase64(blob) {
      return new Promise((resolve, reject) => {
        const fileReader = new FileReader();
        fileReader.onload = (e) => {
          resolve(e.target.result);
        };
        // readAsDataURL
        fileReader.readAsDataURL(blob);
        fileReader.onerror = () => {
          reject(new Error("blobToBase64 error"));
        };
      });
    },
    /**
     * 下载到本地
     */
    downloadParagraph(list, kndex) {
      this.$store.commit("templateStage/SETLISTNOTE", list);
      this.$emit("saveAll",kndex+1,1)
    },
    /**
     * 保存到剪切版
     */
    async saveToClipBoard(stage) {},
    //添加文字
    addTextClick() {
      this.$emit("add");
    },
    //添加图片
    addPicClick(e) {
      e.stopPropagation();
      const file = e.target.files[0];
      let res = this.$datatools.compressedImage(file);
      res.then((result) => {
        const reader = new FileReader();
        reader.onload = (res) => {
          let obj = {
            src: res.target.result,
            name: "本地图片",
          };
          this.$emit("addpic", obj);
        };
        reader.readAsDataURL(result);
      });
    },
    picturelayerclick(name, i) {
      if (name.indexOf("back") != -1) return;
      else this.$emit("layer", name);
    },
    textconBlur(e) {
      if (this.historylist.length == 0) this.$emit("deductchild");
      let text = this.$datatools.TtoDBC(e.target.innerText);
      let obj = {};
      obj.originaltext = text; //originaltext
      obj.onetext = text[0]; //onetext
      if (this.verticaltext) text = this.$datatools.lineFeedCutData(text);
      obj.text = text; //onetext:
      obj.lineNum = this.$datatools.lineNumData(text); //行
      obj.spacingNum = this.$datatools.lineNumData(text); //列
      this.$store.commit("templateStage/DASHITOU", obj);
      this.$emit("deductchild");
    },
    formwork32() {
      if (this.konvaid === 5) {
        this.dashitou26 = true;
        // this.listNote.forEach((v) => {
        //   if (v.config.name == "context2") {
        this.context = this.listNote[0].config.originaltext;
        this.verticaltext = this.listNote[0].config.verticaltext;
        // }
        // });
      } else this.dashitou26 = false;
    },
    setRule() {
      var arr = this.formulafa;
      if(typeof arr == "object"){
        this.formruleArr = arr
      }
      else if(typeof arr == "string"){
        // console.log(arr);
        // console.log(JSON.parse(arr));
        let str = arr
        var times =0;
        let fixedstr=""
        for (let index = 0; index < str.length; index++) {
          if (str[index]==',') {
            times++;
          }
        }
        console.log(times);
        if (times===0) {
          var totextArr = str.split("")
          totextArr.shift()
          totextArr.shift()
          totextArr.pop()
          totextArr.pop()
          let oneText = totextArr.join("")
          let oneArr = [oneText]
          this.formruleArr = oneArr;
        }else{
          this.formruleArr = JSON.parse(arr)
          console.log(arr);
          
        }
      }
      else if(!this.rules){
        this.formruleArr = []
      }
      else if (typeof this.rules == "string") {
        this.formruleArr = JSON.parse(this.rules)
      }else if(typeof this.rules == "object"){
        this.formruleArr = this.rules
      }
      console.log(this.formulafa);
      this.formulaArrText = this.formulafa
    },
    /**
     * 获取批量生成保存到剪切版中的内容
     */
    getClipBoardAll() {},
  },
  created() {
    console.log(this.formruleArr);
    let saveText;
    if(this.templateAllText){
      this.alltext = this.templateAllText;
      saveText = this.alltext.trim();
      let poetry = saveText.split("\n\n");
      this.poetry = poetry
        //多段文字才有批量下载
      this.downloadAllShow= poetry.length>1
    }
    this.allTextShow = this.formulafa.length!=0
  },
  mounted() {
    this.formwork32();
  },
  beforeUpdate() {
    this.formwork32();
  },
  updated() {
    this.formwork32();
  },
  watch: {
    formulafa: {
      handler(newVal, oldVal) {
        if (newVal && newVal.length >= 0) {
          // this.alltext = null;
          this.allTextShow = this.formulafa.length != 0;
          this.setRule();
        }
      },
      immediate: true,
    },
    temid: {
      handler(newVal, oldVal) {
        if (newVal != oldVal) {
          this.alltext = null;
        }
      },
      immediate: true,
    },
  },
  beforeDestroy() {},
};
</script>

<style lang="less" scoped>
@import "../../assets/styles/frame.less";
.text_queding_bot{
  margin-bottom:20px ;
}
.text_queding{
  width: 100%;
  background-color: rgb(212, 212, 212);
  border-radius:17px;
  height: 26px;
  .cen();
}
.butt {
  margin-bottom: 16px;
}
.layers {
  overflow-y: auto;

  &::-webkit-scrollbar {
    width: 0px !important;
  }

  padding: 0 20px;
  .holistic();
  .mark{
    position: absolute;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background: rgba(33, 33, 33, 0.24);
    z-index: 100;
  }
  .layers_tit {
    font-size: 16px;
    margin-bottom: 22px;
  }
  .picture_button {
    position: relative;
    cursor: pointer;
    input {
      position: absolute;
      top: 0 !important;
      left: 0 !important;
      right: 0 !important;
      bottom: 0 !important;
      opacity: 0 !important;
      z-index: 999;
      opacity: 0;
    }
  }
  .picture_layer_P {
    font-size: 16px;
    margin-bottom: 5px;
    font-weight: bold;
  }
  .picture_layers {
    width: 100%;
    border-radius: 6px;
    margin-bottom: 22px;
    font-size: 14px;
    // overflow: hidden;
    // border: 1px solid #e9eee9;
    // margin-top: 22px;
    // padding-right: 3px;
    & > div {
      width: 100%;
      height: 100%;
      overflow-y: auto;
      .picture_layer {
        width: 100%;
        overflow-x: hidden;
        // scroll-/: ;
        // height: 28px;
        padding: 3px 13px;
        min-height: 14px;
        // padding-left: 13px;
        border: 1px solid #e9eee9;
        cursor: pointer;
      }
      .picture_layer:last-child {
        border-bottom: 1px solid transparent;
      }
    }
  }
  .formulaarea {
    display: flex;
    align-items: center;
  }
  .alltext {
    margin: 0 0 20px 0;
    width: 100%;
    min-height: 140px;
    padding: 10px 4px;
    font-size: 20px;
    border-radius: 4px;
    background: #f6f6f6;
    resize: none;
    // box-shadow: 5px 5px skyblue;
  }
}
.text_con_all_text {
  width: 100%;
  // border-radius: 10px;
  overflow: hidden;
  margin-bottom: 10px;
  background: #f6f6f6;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}
.text_con {
  width: 1000px;
  min-height: 140px;
  //bottom: 16px

  // writing-mode: vertical-rl;
  .text_blur {
    width: 1000px;
    min-height: 20px;
    font-size: 20px;
    white-space: break-spaces;
    padding: 10px 4px;
    line-height: 26px;
    -webkit-user-modify: read-write-plaintext-only; //只能输入纯文本
    -moz-user-modify: read-write-plaintext-only; //只能输入纯文本
    &:focus {
      outline: none;
    }
  }
}
</style>